# -*- coding: utf-8 -*-
import base64
import json
import logging
import os
import time
from datetime import date
from datetime import datetime, timedelta

from odoo import http
from odoo.http import Response, request

_logger = logging.getLogger(__name__)
test = True
test_fields = ['is_check']
handel_faults = ['问题牌(白牌)', '问题牌(黄牌)', '问题牌(红牌)', '问题牌(事故苗子)', '问题牌（黄牌）', '问题牌（红牌）', '问题牌（事故苗子）']


def get_error_message(msg):
    if msg == 1:
        msg = '创建失败'
    elif msg == 2:
        msg = '修改成功'
    elif msg == 3:
        msg = '修改失败'
    elif msg == 4:
        msg = '删除成功'
    elif msg == 5:
        msg = '删除失败'
    elif msg == 0:
        msg = '确认提交的信息'
    elif msg == -1:
        msg = "暂无数据"
    return Response(json.dumps(msg), content_type='application/json;charset=utf-8', status=200)


def this_year_month(this_time=None, month=0):
    import time, datetime, calendar
    # 当前时间
    now_time = datetime.datetime.now()
    # 如果传入时间，使用传入时间
    if this_time:
        if this_time == datetime.datetime:
            now_time = this_time
        else:
            now_time = datetime.datetime.strptime(this_time[:10], "%Y-%m-%d")
    now_time_mk = time.mktime(now_time.timetuple())  # 当前时间戳
    if month < 0:
        if now_time.month <= abs(month):
            compute_date = "%s-%s-%s" % (now_time.year - 1, 12 + now_time.month + month, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")
        else:
            compute_date = "%s-%s-%s" % (now_time.year, now_time.month + month, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")
    if month > 0:
        if now_time.month + abs(month) > 12:
            compute_date = "%s-%s-%s" % (now_time.year + 1, now_time.month + month - 12, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")
        else:
            compute_date = "%s-%s-%s" % (now_time.year, now_time.month + month, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")

    # 本月第一天
    datetime.timedelta(days=31)
    last_day = calendar.monthrange(now_time.year, now_time.month)[1]
    first_time = datetime.datetime(now_time.year, now_time.month, 1).strftime("%Y-%m-%d %H:%M:%S")
    last_time = datetime.datetime(now_time.year, now_time.month, last_day, 23, 59, 59).strftime("%Y-%m-%d %H:%M:%S")

    return (first_time, last_time)


def multi_cont(l1, l2):
    set1 = set(l1)
    set2 = set(l2)
    if len(set1 & set2):
        return True
    else:
        return False


def data2args(data, args, fields):
    if 'id' in data.keys():
        id = data['id']
        if id:
            args += [('id', '=', id)]
    if 'card_id' in data.keys():
        card_id = data['card_id']
        if card_id:
            args += [('card_id', '=', card_id)]
    if 'staff_id' in data.keys():
        staff_id = data['staff_id']
        if staff_id:
            args += [('staff_id', '=', int(staff_id))]
    if 'warning_staff_id' in data.keys():
        warning_staff_id = data['warning_staff_id']
        if warning_staff_id:
            args += [('warning_staff_id', '=', int(warning_staff_id))]
    if 'self_num' in data.keys():
        args += [('fault_nature_type', '=', 'self')]
    if 'check_num' in data.keys():
        args += [('fault_nature_type', '=', 'other')]
    if 'other_num' in data.keys():
        args += [('fault_nature_type', '=', 'check')]
    if 'correct' in data.keys():
        # _logger.info('查询纠错记录')
        args += [('is_test2', '=', True)]
    if 'tolerant' in data.keys():
        # _logger.info('查询容错记录')
        args += [('is_test', '=', True)]
    if 'help' in data.keys():
        # _logger.info('查询容错记录')
        args += [('is_lose2', '=', True)]
    if 'ws_id' in data.keys():
        ws_id = data['ws_id']
        if ws_id:
            args += [('ws_id', '=', ws_id)]
    if 'name' in data.keys():
        name = data['name']
        if name:
            staffs = request.env['cr.emp.staff'].search([('name', 'like', name)])
            if len(staffs.ids) > 0:
                staff_id = staffs[0].id
                args += [('staff_id', '=', staff_id)]
            else:
                args += [('staff_id', '=', -1)]
    if 'year' in data.keys():
        year = data['year']
        if year:
            args += [('year', '=', year)]
    if 'level' in data.keys():
        level = data['level']
        if level:
            args += [('level', '=', level)]
    if 'month' in data.keys():
        month = data['month']
        if month:
            args += [('month', '=', month)]
    if 'type' in data.keys():
        type = data['type']
        if type:
            args += [('type', '=', type)]
    if 'fault_type' in data.keys():
        # _logger.info('1111111111111111111111111111111111111111')
        fault_type = data['fault_type']
        if fault_type == 'self':
            args += [('fault_nature_type', '=', 'self')]
        if fault_type == 'other':
            args += [('fault_nature_type', '=', 'other')]
        if fault_type == 'check':
            args += [('fault_nature_type', '=', 'check')]
    if 'cr_emp_ws_id' in data.keys() and 'ws_id' in fields:
        month = data['cr_emp_ws_id']
        if month:
            args += [('ws_id', '=', month)]
    # _logger.info(str(args))
    return args


def get_result(result, args):
    # # #_logger.info(args)
    list1 = []
    for i in result:
        dict = {}
        for j in args:
            if j in i.keys():
                data = type_to_json(i[j])
                if j in ['team_id', 'dep_id', 'ws_id', 'post_id', 'faullt_tupe_id', 'staff_id']:
                    if i[j]:
                        dict.update({j + '_id': i[j][0]})
                        dict.update({j + '_name': i[j][1]})
                # #_logger.info(data)
                dict.update({j: data})
                if j == 'birthday':
                    dict.update({j: data[:10]})
                if j == 'fault_nature_type':
                    if i[j] == 'self':
                        dict.update({j: '自我暴露'})
                    if i[j] == 'other':
                        dict.update({j: '他人指出'})
                    if i[j] == 'check':
                        dict.update({j: '检查发现'})
                if j == 'fault_nature_id':
                    fault_nature = request.env['cr.emp.fault.nature'].search_read([('id', 'in', i[j])],
                                                                                  fields=['id', 'name'])
                    dict.update({j: fault_nature})
                if j == 'level':
                    # # #_logger.info(type(i[j]))
                    if i[j]:
                        dict.update({j: int(i[j])})
            #
        list1.append(dict)
        # _logger.info(list1)
    return list1
    try:
        pass
    except:
        # #_logger.info(args)
        return


def format_datetime(Datetime):
    if len(Datetime) == 10:
        Datetime = (datetime.strptime(Datetime + ' 00:00:00', '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)).strftime(
            '%Y-%m-%d %H:%M:%S')

    Datetime = Datetime.replace('T', ' ')
    Datetime = Datetime.replace('Z', '')
    Datetime = Datetime.replace('+', ' ')
    if '.' in Datetime:
        Datetime = Datetime[:-4]
    Datetime = (datetime.strptime(Datetime, '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S')
    # # #_logger.info(Datetime)
    return Datetime


def add_to_args(result, *args):
    _logger.info('修改内容原始')
    _logger.info(str(args))
    keys = args[0]
    values = args[1]
    # if test == True:
    # #_logger.info('转换参数')
    keys = args[0]
    values = args[1]
    for i in keys:
        # # # #_logger.info(i)
        # # # #_logger.info(values[i])
        if i in values.keys():
            if i in test_fields:
                # #_logger.info(i)
                # #_logger.info(values[i])
                pass
            if i in ['id']:
                # _logger.info('修改')
                pass
            if values[i] == 'false':
                # #_logger.info('false')
                result.update({i: False})
            # if values[i]:
            elif i in ['team_id', 'dep_id', 'ws_id', 'help_staff_id', 'post_id', 'fault_type_id', 'staff_id',
                       'add_staff_id', 'warning_staff_id']:
                if values[i]:
                    result.update({i: int(values[i])})
            elif i == 'birthday' or i == 'time' or i == 'observe_start_time' or i == 'observe_end_time':
                result.update({i: format_datetime(values[i])})
            elif i == 'create_date':
                result.update({i: values[i].strftime('%Y-%m-%d %H:%M:%S')})
            elif i == 'cr_emp_ws_id':
                result.update({'ws_id': int(values[i])})
            elif i == 'fault_nature_id':
                # _logger.info(values[i])
                fault_nature_ids = values[i].split(',')
                fault_nature_ids = [int(j) for j in fault_nature_ids]
                result.update({'fault_nature_id': fault_nature_ids})
            else:
                result.update({i: values[i]})

    # #_logger.info('转换完成')
    # #_logger.info(result)
    return result
    for i in keys:
        # # # #_logger.info(i)
        # # # #_logger.info(values[i])
        if i in values.keys():
            if i in test_fields:
                # #_logger.info(i)
                # #_logger.info(values[i])
                passa
            if values[i] == 'false':
                # #_logger.info('false')
                result.update({i: False})
            # if values[i]:
            elif i in ['team_id', 'dep_id', 'ws_id', 'post_id', 'fault_type_id', 'staff_id']:
                result.update({i: int(values[i])})
            elif i == 'birthday' or i == 'time':
                result.update({i: format_datetime(values[i])})
            elif i == 'create_date':
                result.update({i: values[i].strftime('%Y-%m-%d %H:%M:%S')})
            elif i == 'cr_emp_ws_id':
                result.update({'ws_id': int(values[i])})
            elif i == 'fault_nature_id':
                fault_nature_ids = json.decoder(values[i])
                result.update({'fault_nature_id': fault_nature_ids})
            else:
                result.update({i: values[i]})
        return result
    try:
        pass
    except:
        # # #_logger.info(keys,values)
        return


def type_to_json(obj):
    if isinstance(obj, datetime):
        return obj.strftime('%Y-%m-%d %H:%M:%S')
    elif isinstance(obj, date):
        return obj.strftime('%Y-%m-%d')
    else:
        return obj


def change_base_limit(data1, data2):
    data = base_limit.copy()
    if 'page' in data2.keys():
        data.update({'page': data2['page']})
    else:
        data.update({'page': data1['page']})
    if 'limit' in data2.keys():
        data.update({'limit': data2['limit']})
    else:
        data.update({'limit': data1['limit']})
    if 'sorted' in data2.keys():
        if data2['sorted']:
            # if data12['sorted']=='':
            sorted = data2['sorted'].replace(',', ' ')
            data.update({'sorted': sorted})
    else:
        data.update({'sorted': data1['sorted']})
    if 'count' in data2.keys():
        data.update({'count': data2['count']})
    else:
        data.update({'count': data1['count']})
    data.update({'offset': (data['page'] - 1) * data['limit']})
    return data


base_limit = {
    'page': 1,
    'limit': 1000000000000,
    'sorted': None,
    'count': False,
    'offset': 0
}


class CrEmpSearchController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name']

    @http.route('/emp/base/search/count', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def search_count1(self, **kwargs):
        model = kwargs.get('model').replace('_', '.')
        ws_id = kwargs.get('ws_id')
        staff_id = kwargs.get('staff_id')
        year = kwargs.get('year')
        month = kwargs.get('month')
        name = kwargs.get('name')
        level = kwargs.get('level')
        args = []
        if ws_id:
            args += [('ws_id', '=', int(ws_id))]
        if staff_id:
            args += [('staff_id', '=', int(staff_id))]
        if year:
            args += [('year', '=', year)]
        if month:
            args += [('month', '=', month)]
        if name:
            args += [('name', 'like', name)]
        if level:
            args += [('level', '=', level)]
        if model == 'user':
            args += [('cr_emp_type', '!=', 'none')]
        result = request.env['res.users' if model == 'user' else 'cr.emp.%s' % model].sudo().search_count(args)
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)


class CrEmpDepController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name']

    @http.route('/emp/base/dep/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def dep_list(self, data=None):
        # # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.dep'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                           order=limit['sorted'])
            result = get_result(result, ['id'] + fields)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.dep'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                  order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                fields = ['id'] + fields
                result = request.env['cr.emp.dep'].search_read(domain=[('id', 'in', ids)],
                                                               fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/base/dep/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def dep_create(self, **kwargs):

        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        result = request.env['cr.emp.dep'].create(args)
        id = result[0].id
        fields = self.get_fields()
        result = request.env['cr.emp.dep'].search_read(domain=[('id', '=', id)],
                                                       fields=fields + ['id'])
        result = get_result(result, fields + ['id'])
        # # #_logger.info(result)
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        if result:
            id = result[0].id
            fields = self.get_fields()
            result = request.env['cr.emp.dep'].search_read(domain=[('id', '=', id)],
                                                           fields=fields + ['id'])
            result = get_result(result, fields + ['id'])
            # # #_logger.info(result)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        else:
            return get_error_message(1)

    @http.route('/emp/base/dep/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def dep_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.dep'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        # _logger.info(args)
        result.write(args)

        return get_error_message(2)
        try:
            return
        except:
            return get_error_message(3)

    @http.route('/emp/base/dep/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def dep_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.dep'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpWsController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'dep_id']

    @http.route('/emp/base/ws/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def ws_list(self, data=None):
        # # #_logger.info(data)
        if data:
            data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            _logger.info('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
            limit = change_base_limit(limit, data)
            if limit['sorted'] == 'ws_id':
                limit['sorted'] = None
            args = data2args(data, args, fields)
            _logger.info(str(args))
            result = request.env['cr.emp.workshop'].search(args=args, offset=limit['offset'],
                                                           limit=limit['limit'],
                                                           order=limit['sorted']).read()
            result = get_result(result, fields + ['id'])
            _logger.info(result)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        if limit['sorted'] == 'ws_id':
            limit['sorted'] = None
        result = request.env['cr.emp.workshop'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                       order=limit['sorted'], count=limit['count'])
        if result:
            ids = result.ids
            result = request.env['cr.emp.workshop'].search_read(domain=[('id', 'in', ids)],
                                                                fields=['id'] + fields)
            result = get_result(result, ['id'] + fields)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        else:
            return get_error_message('暂无数据')
        try:
            pass
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/base/ws/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def ws_create(self, **kwargs):
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.workshop'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.workshop'].search_read(domain=[('id', '=', id)],
                                                                    fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return Response(json.dumps('创建失败'), content_type='application/json;charset=utf-8', status=200)
        except:

            return Response(json.dumps('创建失败'), content_type='application/json;charset=utf-8', status=200)

    @http.route('/emp/base/ws/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def ws_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.workshop'].search(args=[('id', '=', id)])
        try:
            result.write(args)
            return Response(json.dumps('修改成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('修改失败'), content_type='application/json;charset=utf-8', status=200)

    @http.route('/emp/base/ws/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def ws_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.workshop'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpTeamController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'dep_id', 'ws_id']

    @http.route('/emp/base/team/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def team_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.team'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                            order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.team'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                   order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.team'].search_read(domain=[('id', 'in', ids)],
                                                                fields=['id'] + fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/base/team/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def team_create(self, **kwargs):
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.team'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.team'].search_read(domain=[('id', '=', id)],
                                                                fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/base/team/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def team_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.team'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/base/team/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def team_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.team'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpPostController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name']

    @http.route('/emp/base/post/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def post_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.post'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                            order=limit['sorted'])
            result = get_result(result, ['id'] + fields)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.post'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                   order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                fields = ['id'] + fields
                result = request.env['cr.emp.post'].search_read(domain=[('id', 'in', ids)],
                                                                fields=['id'] + fields)
                result = get_result(result, ['id'] + fields)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/base/post/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def post_create(self, **kwargs):
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.post'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.post'].search_read(domain=[('id', '=', id)],
                                                                fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/base/post/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def post_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.post'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/base/post/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def post_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.post'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpFaultTypeController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'is_important']

    @http.route('/emp/base/fault_type/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def fault_type_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.fault.type'].search_read(domain=args, offset=limit['offset'],
                                                                  limit=limit['limit'],
                                                                  order=limit['sorted'])
            result = get_result(result, ['id'] + fields)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.fault.type'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                         order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                fields = ['id'] + fields
                result = request.env['cr.emp.fault.type'].search_read(domain=[('id', 'in', ids)],
                                                                      fields=['id'] + fields)
                result = get_result(result, ['id'] + fields)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/base/fault_type/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def fault_type_create(self, **kwargs):
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.fault.type'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.fault.type'].search_read(domain=[('id', '=', id)],
                                                                      fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/base/fault_type/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def fault_type_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.fault.type'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/base/fault_type/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def fault_type_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.fault.type'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpFaultNatureController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'type', 'is_default', 'tolerate_correct', 'sub_score', 'to_lose', 'add_score',
                'add_score', 'priority', 'fight']

    @http.route('/emp/base/fault_nature/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def fault_nature_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.fault.nature'].search_read(domain=args, offset=limit['offset'],
                                                                    limit=limit['limit'],
                                                                    order=limit['sorted'])
            result = get_result(result, ['id'] + fields)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.fault.nature'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                           order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                fields = ['id'] + fields
                result = request.env['cr.emp.fault.nature'].search_read(domain=[('id', 'in', ids)],
                                                                        fields=['id'] + fields)
                result = get_result(result, ['id'] + fields)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/base/fault_nature/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def fault_nature_create(self, **kwargs):
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(type(args['to_lose']))
        try:
            result = request.env['cr.emp.fault.nature'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields() + ['id']
                result = request.env['cr.emp.fault.nature'].search_read(domain=[('id', '=', id)],
                                                                        fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/base/fault_nature/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def fault_nature_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.fault.nature'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/base/fault_nature/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def fault_nature_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.fault.nature'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpStaffController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['card_id', 'name', 'sex', 'ws_id', 'team_id', 'post_id', 'birthday', 'id', 'photo_url']

    def get_update_fields(self):
        return ['card_id', 'name', 'sex', 'team_id', 'post_id', 'birthday', 'photo_url']

    @http.route('/emp/score/staff/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def staff_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.staff'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                             order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.staff'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                    order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.staff'].search_read(domain=[('id', 'in', ids)],
                                                                 fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/staff/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def staff_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.staff'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.staff'].search_read(domain=[('id', '=', id)],
                                                                 fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/staff/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def staff_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {}
        # # #_logger.info(kwargs)
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        result = request.env['cr.emp.staff'].search(args=[('id', '=', id)])
        # # #_logger.info(result)
        if not result:
            return get_error_message(0)
        # # #_logger.info("request.env['cr.emp.staff'].search(args=[('id', 'in', %s)]).write(args)" % (id, str(args)))
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/staff/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def staff_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.staff'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(-1)
        try:
            result.unlink()
            if result:
                return get_error_message(4)
        except:
            return get_error_message(5)

    @http.route('/emp/base/card/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def staff_card_search(self, data=None):
        data = json.loads(data)
        card_id = data['card_id']
        fields = self.get_fields()
        # #_logger.info(card_id)
        result = request.env['cr.emp.staff'].search_read([('card_id', '=', str(card_id))])
        if not result:
            return get_error_message(-1)
        try:
            result = get_result(result, fields)
            if result:
                return get_error_message(result)
        except:
            return get_error_message(5)

    @http.route('/emp/score/staff/upload', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def upload_img(self, *args, **kwargs):
        _logger.info(str(kwargs))
        name = kwargs['name']
        image = kwargs['image']
        type = name.split('.')[-1]
        if type not in ['jpg', 'png', 'jepg']:
            return {'code': 0, 'msg': '请检查图片格式'}
        # baseurl = 'http://47.105.136.70:8069/cr_hd_emp/static/img/'
        baseurl = 'http://10.80.66.29:8069/cr_hd_emp/static/img/'
        basedir = '/opt/odoo/server/odoo/addons/cr_hd_emp/static/img/'
        # basedir = '/opt/odoo/addons2/cr-odoo/addons/cr_hd_emp/static/img/'
        dirname = str(int(time.time()))
        filedir = basedir + dirname
        # print(filedir)
        # if type == 'jpg' or type == 'jepg':
        #     data = image[23:]
        # elif type == 'png':
        #     data = image[22:]
        # print(data)
        filename = str(int(time.time())) + '.' + type
        _logger.info(str(filename))

        # print('进入上传')
        os.mkdir(filedir)
        # print(filedir + '/' + filename)
        imgdata = base64.b64decode(image)
        _logger.info(str(filedir + '/' + filename))
        with open(filedir + '/' + filename, 'wb') as f:
            f.write(imgdata)
        result = {'code': 1, 'msg': '上传成功', 'url': baseurl + dirname + '/' + filename}
        result = json.dumps(result)
        return get_error_message(result)
        try:
            pass
        except:
            result = {'code': 0, 'msg': '上传失败'}
            result = json.dumps(result)
            return get_error_message(result)

    def D_BASE64(self, origStr):
        # base64 decode should meet the padding rules
        if (len(origStr) % 3 == 1):
            origStr += "=="
        elif (len(origStr) % 3 == 2):
            origStr += "="

        origStr = bytes(origStr, encoding='utf8')
        dStr = base64.b64decode(origStr).decode()
        # print("BASE64 Decode result is: \n" + dStr)
        return dStr


class CrEmpHelpController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'time', 'lose_detail_ids']

    @http.route('/emp/score/help/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def help_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.help'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                            order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.help'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                   order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.help'].search_read(domain=[('id', 'in', ids)],
                                                                fields=['id'] + fields)
                result = get_result(result, ['id'] + fields)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/help/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def help_create(self, **kwargs):
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.help'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.help'].search_read(domain=[('id', '=', id)],
                                                                fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/help/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def help_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.help'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/help/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def help_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.help'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpLoseItemController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):

        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'time',
                'help_card_id', 'help_staff_id',
                'help_name', 'observe_end_time',
                'lose_fault', 'measures',
                'help_id', 'id']

    def get_update_fields(self):
        return ['staff_id', 'help_staff_id', 'time', 'observe_time',
                'lose_fault', 'measures', 'observe_end_time']

    @http.route('/emp/score/lose_item/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def lose_item_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.lose.item'].search_read(domain=args, offset=limit['offset'],
                                                                 limit=limit['limit'],
                                                                 order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        result = request.env['cr.emp.lose.item'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                        order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.lose.item'].search_read(domain=[('id', 'in', ids)],
                                                                     fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/lose_item/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def lose_item_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.lose.item'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.lose.item'].search_read(domain=[('id', '=', id)],
                                                                     fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/lose_item/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def lose_item_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.lose.item'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/lose_item/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def lose_item_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.lose.item'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpPromiseController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'pledge_ids', 'id']

    @http.route('/emp/score/promise/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def promise_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            _logger.info(args)
            result = request.env['cr.emp.promise'].search_read(domain=args, offset=limit['offset'],
                                                               limit=limit['limit'],
                                                               order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.promise'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                      order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.promise'].search_read(domain=[('id', 'in', ids)],
                                                                   fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')


class CrEmpPledgeController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'promise_id', 'year', 'month', 'detail',
                'id', 'create_date']

    def get_update_fields(self):
        return ['staff_id', 'year', 'month', 'detail']

    @http.route('/emp/score/pledge/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def pledge_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.pledge'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                              order=limit['sorted'])
            # _logger.info('\n预警条目数据%s' % str(result))
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.pledge'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                     order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.pledge'].search_read(domain=[('id', 'in', ids)],
                                                                  fields=fields)
                # _logger.info('\n预警条目数据%s'%str(result))
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/pledge/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def pledge_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.pledge'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.pledge'].search_read(domain=[('id', '=', id)],
                                                                  fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/pledge/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def pledge_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        # _logger.info(id)
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # _logger.info(args)
        result = request.env['cr.emp.pledge'].search(args=[('id', '=', int(id))])
        # _logger.info(str(result.read()))
        if not result:
            return get_error_message(0)
        result.write(args)
        # _logger.info(str(result.read()))
        return get_error_message(2)
        try:
            pass
        except:
            return get_error_message(3)

    @http.route('/emp/score/pledge/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def pledge_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.pledge'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)


class CrEmpScoreController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['level', 'self_num', 'other_num', 'check_num', 'name', 'card_id', 'ws_id', 'team_id', 'post_id',
                'staff_id', 'year', 'month', 'add_score', 'sub_score',
                'total_score', 'add_score_detail_ids', 'sub_score_detail_ids', 'is_lose', 'id']

    def get_update_fields(self):
        return ['staff_id', 'year', 'month']

    @http.route('/emp/score/score/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def score_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            # # #_logger.info('提供条件')
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            # # #_logger.info(args)
            result = request.env['cr.emp.score'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                             order=limit['sorted'])
            # # #_logger.info(result)
            result = get_result(result, fields + ['id'])
            # _logger.info(result)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.score'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                    order=limit['sorted'], count=limit['count'])
        # # #_logger.info(result)
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.score'].search_read(domain=[('id', 'in', ids)], offset=limit['offset'],
                                                                 limit=limit['limit'],
                                                                 order=limit['sorted'])
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)

                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')


class CrEmpScoreItemController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'staff_id',
                'time', 'fault_type_id',
                'sub_score', 'add_score',
                'fault_nature_type', 'fault_nature_id',
                'survey', 'add_card_id',
                'add_staff_id', 'add_name',
                'observe_start_time', 'observe_end_time',
                'id', 'observe_time', 'detail', 'is_lose2']

    def get_update_fields(self):
        return ['survey', 'staff_id', 'add_card_id', 'add_staff_id', 'score_card_id', 'time', 'observe_time',
                'fault_type_id', 'fault_nature_id', 'observe_start_time', 'observe_end_time', 'sub_score', 'add_score']

    @http.route('/emp/score/score_item/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def score_item_list(self, data=None):
        # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            # _logger.info('数据'+str(data))
            limit = change_base_limit(limit, data)
            data2 = data.copy()
            data2.pop('staff_id')
            args = data2args(data2, args, fields)
            _logger.info('查询条件1' + str(args))
            if 'name' in data.keys():
                name = data['name']
                if name:
                    staffs = request.env['cr.emp.staff'].search([('name', 'like', name)])
                    if len(staffs.ids) > 0:
                        staff_id = staffs[0].id
                        args += ['|', ('staff_id', '=', int(staff_id)), ('add_staff_id', '=', int(staff_id))] + args
                    else:
                        args = ['|', ('staff_id', '=', -1), ('add_staff_id', '=', -1)] + args
            else:
                staff_id = data.get('staff_id')
                args = ['|', ('staff_id', '=', int(staff_id)), ('add_staff_id', '=', int(staff_id))] + args
            _logger.info('查询条件2' + str(args))
            result = request.env['cr.emp.score.item'].search_read(domain=args, offset=limit['offset'],
                                                                  limit=limit['limit'],
                                                                  order=limit['sorted'])
            _logger.info('查询结果1' + str(result))
            for i in result:
                if 'tolerate' not in data.keys() and 'correct' not in data.keys():
                    if i.get('add_staff_id'):
                        if int(i.get('add_staff_id')[0]) == int(data.get('staff_id')):
                            i.update({'name': i.get('add_staff_id')[1]})
                            i.update({'card_id': i.get('add_card_id')})
                            i.update({'sub_score': i.get('add_score')})
            result = get_result(result, fields + ['id'])
            _logger.info('查询结果2' + str(result))
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.score.item'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                         order=limit['sorted'], count=limit['count'])
        # #_logger.info(result)
        ids = result.ids
        result = request.env['cr.emp.score.item'].search_read(domain=[('id', 'in', ids)],
                                                              fields=fields)
        # #_logger.info('step2')

        result = get_result(result, fields)
        # #_logger.info('step3')
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        try:
            if result:
                pass
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/score_item/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def score_item_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        result = request.env['cr.emp.score.item'].create(args)
        if result:
            id = result[0].id
            fields = self.get_fields()
            result = request.env['cr.emp.score.item'].search_read(domain=[('id', '=', id)],
                                                                  fields=fields)
            result = get_result(result, fields + ['id'])
            # # #_logger.info(result)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        else:
            return get_error_message(1)
        try:
            result = request.env['cr.emp.score.item'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.score.item'].search_read(domain=[('id', '=', id)],
                                                                      fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/score_item/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def score_item_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        _logger.info('修改内容')

        _logger.info(str(args))
        result = request.env['cr.emp.score.item'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)

        result.write(args)
        return get_error_message(2)

    @http.route('/emp/score/score_item/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def score_item_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.score.item'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)

    @http.route('/emp/score/score_item/get_score', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def score_item_get_score(self, **kwargs):
        result = {'sub_score': 0, 'add_score': 0}
        time1 = this_year_month(kwargs['time1'])
        args = kwargs
        if len(kwargs['fault_nature_id']) > 1:
            args.update({'fault_nature_id': [str(i) for i in kwargs['fault_nature_id'].split(',')]})
        else:
            if not kwargs['fault_nature_id']:
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            args.update({'fault_nature_id': [int(kwargs['fault_nature_id'])]})
        args.update({'fault_nature_ids': kwargs['fault_nature_ids'].split(',')})
        times = 1 + request.env['cr.emp.score.item'].search_count(
            [('time', '>', time1[0]), ('time', '<', time1[1]), ('staff_id', '=', int(args.get('staff_id'))),
             ('fault_type_id', '=', int(args.get('fault_type_id')))])
        if args.get('fault_nature_type') == 'self':
            fault_natures = args.get('fault_nature_ids')
            if '不重复问题' in fault_natures:
                result.update({'sub_score': -2})
            if '问题重复' in fault_natures:
                result.update({'sub_score': -2 * times})

            if '违反承诺' in fault_natures:
                result.update({'sub_score': -10})
            if '重复违反承诺' in fault_natures:
                result.update({'sub_score': -20})
        elif args.get('fault_nature_type') == 'other':
            fault_natures = args.get('fault_nature_ids')
            if '不重复问题' in fault_natures:
                result.update({'sub_score': -2})
                result.update({'add_score': 2})
            if '问题重复' in fault_natures:
                result.update({'sub_score': -2 * times})
                result.update({'add_score': 2})

            if '违反承诺' in fault_natures:
                result.update({'sub_score': -20})
                result.update({'add_score': 5})

            if '重复违反承诺' in fault_natures:
                result.update({'sub_score': -40})
                result.update({'add_score': 5})
        elif args.get('fault_nature_type') == 'check':
            fault_natures = args.get('fault_nature_ids')
            if '问题不重复' in fault_natures:
                result.update({'sub_score': -4})
            if '问题重复' in fault_natures:
                result.update({'sub_score': -4 * times})
            if '问题牌(白牌)' in fault_natures:
                result.update({'sub_score': -5})
            if '问题牌(黄牌)' in fault_natures:
                result.update({'sub_score': -10})
            if '问题牌(红牌)' in fault_natures:
                result.update({'sub_score': -20})
            if '问题牌(事故苗子)' in fault_natures:
                result.update({'sub_score': -30})
            if '违反承诺' in fault_natures:
                result.update({'sub_score': -40})
            if '重复违反承诺' in fault_natures:
                result.update({'sub_score': -40})
            if '加分' in fault_natures:
                result.update({'sub_score': 5})
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

    @http.route('/emp/score/score_item/get_observe', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def is_set_observe(self, **values):
        result = {}
        is_in_observe = request.env['cr.emp.score.item'].is_in_observe(values.get('staff_id'), values.get('time1'))
        if is_in_observe:
            return Response(json.dumps('员工在纠错期中。'), content_type='application/json;charset=utf-8', status=200)
        handle_nums = request.env['cr.emp.score.item'].handle_nums(values.get('staff_id'), values.get('time1'))
        values.update({'fault_nature_id': values.get('fault_nature_id').split(',')})
        is_handle = request.env['cr.emp.score.item'].is_handle(values)
        if not is_handle:
            return Response(json.dumps('问题未发牌中。'), content_type='application/json;charset=utf-8', status=200)
        _logger.info('问题牌  %s  ，设置纠错期' % str(is_handle))
        _logger.info('第%s张问题牌，设置纠错期' % str(handle_nums))
        if is_handle and handle_nums == 1:
            _logger.info('第二张问题牌，设置纠错期')
            return Response(json.dumps({'is_set_observe': 1}), content_type='application/json;charset=utf-8',
                            status=200)
        is_important = request.env['cr.emp.score.item'].is_important(values)
        important_nums = request.env['cr.emp.score.item'].important_nums(values.get('staff_id'), values.get('time1'))
        _logger.info('问题牌  %s  ，设置纠错期' % str(is_important))
        _logger.info('第%s张问题牌，设置纠错期' % str(important_nums))
        if is_important and important_nums == 0:
            _logger.info('第一张红线问题，设置纠错期')
            return Response(json.dumps({'is_set_observe': 1}), content_type='application/json;charset=utf-8',
                            status=200)
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

    @http.route('/emp/score/score_item/get_index_data', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def get_index_data(self, **values):
        args = []
        if 'ws_id' in values.keys():
            ws_id = values.get('ws_id')
            if ws_id:
                args = [('ws_id', '=', int(ws_id))]
        _logger.info(str(args))
        num1 = request.env['cr.emp.score'].search_count(args + [('level', '=', '0')])
        num2 = request.env['cr.emp.score'].search_count(args + [('level', '=', '1')])
        num3 = request.env['cr.emp.score'].search_count(args + [('level', '=', '2')])
        result = json.dumps([num1, num2, num3])
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

    @http.route('/emp/score/score_item/get_index_data2', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def get_index_data2(self, **values):
        result = []
        if 'ws_id' in values.keys():
            ws_id = values.get('ws_id')
            if ws_id:
                args = [('ws_id', '=', int(ws_id))]
        for i in range(30):
            args = []
            now = datetime.now() - timedelta(days=i)
            _logger.info('\n时间' + str(now))
            start_time = now - timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,
                                         microseconds=now.microsecond)
            last_time = start_time + timedelta(hours=23, minutes=59, seconds=59)
            start_time = datetime.strftime(start_time, "%Y-%m-%d %H:%M:%S")
            last_time = datetime.strftime(last_time, "%Y-%m-%d %H:%M:%S")
            args += [('time', '<', last_time), ('time', '>=', start_time)]
            _logger.info(str(args) + '::::::::::::' + str(last_time) + '::::::::::' + str(start_time))
            num1 = request.env['cr.emp.score.item'].search_count(args)
            result.append(num1)
        return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

    # 判断当月是否有重要问题
    def is_first_handel(self, staff_id, this_time):
        times = this_year_month(this_time)
        first_time = times[0]
        last_time = times[1]
        faults = request.env['cr.emp.score.item'].search_count(
            [('staff_id', '=', staff_id), ('time', '<', last_time), ('time', '>', first_time),
             ('is_handel_fault', '=', True)])
        if faults == 0:
            return True
        else:
            return False

    # 判断是否是当月是否有问题牌
    def is_first_important(self, staff_id, this_time):
        times = this_year_month(this_time)
        first_time = times[0]
        last_time = times[1]
        faults = request.env['cr.emp.score.item'].search_count(
            [('staff_id', '=', staff_id), ('time', '<', last_time), ('time', '>', first_time),
             ('is_important2', '=', True)])
        if faults == 0:
            return True
        else:
            return False

    def is_in_observe(self, staff_id, this_time):
        staff = request.env['cr.emp.staff'].search_count([('id', '=', staff_id),
                                                          ('observe_start_time', '<', this_time),
                                                          ('observe_end_time', '>', this_time)])
        if staff > 0:
            return True
        else:
            return False


class CrEmpStopController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['id', 'detail', 'name', 'create_date']

    def get_update_fields(self):
        return ['detail', 'name']

    @http.route('/emp/score/stop/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def stop_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.stop'].search_read(domain=args, offset=limit['offset'], limit=limit['limit'],
                                                            order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.stop'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                   order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.stop'].search_read(domain=[('id', 'in', ids)],
                                                                fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/stop/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def stop_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.stop'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.stop'].search_read(domain=[('id', '=', id)],
                                                                fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/stop/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def stop_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.stop'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/stop/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def stop_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.stop'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(-1)
        try:
            result.unlink()
            if result:
                return get_error_message(4)
        except:
            return get_error_message(5)


class CrEmpInspireController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['detail', 'create_date', 'is_check', 'card_id', 'end_money', 'name', 'is_lose', 'ws_id', 'team_id',
                'post_id',
                'staff_id', 'add_score', 'sub_score', 'total_score', 'add_money', 'sub_money', 'score_id', 'id', 'year',
                'month']

    def get_update_fields(self):
        return ['is_check', 'detail', 'staff_id', 'is_lose', 'add_money', 'sub_money', 'end_money']

    @http.route('/emp/score/inspire/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def inspire_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.inspire'].search_read(domain=args, offset=limit['offset'],
                                                               limit=limit['limit'],
                                                               order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.inspire'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                      order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.inspire'].search_read(domain=[('id', 'in', ids)],
                                                                   fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/inspire/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def inspire_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        try:
            result = request.env['cr.emp.inspire'].create(args)
            if result:
                id = result[0].id
                fields = self.get_fields()
                result = request.env['cr.emp.inspire'].search_read(domain=[('id', '=', id)],
                                                                   fields=fields)
                result = get_result(result, fields + ['id'])
                # # #_logger.info(result)
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message(1)
        except:
            return get_error_message(1)

    @http.route('/emp/score/inspire/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def inspire_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.inspire'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/inspire/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def inspire_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.inspire'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(-1)
        try:
            result.unlink()
            if result:
                return get_error_message(4)
        except:
            return get_error_message(5)

    @http.route('/emp/score/inspire/get_all', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def inspire_get_all(self, **kwargs):
        now = datetime.now()
        staff_id = kwargs.get('staff_id')
        staff_id = int(staff_id)
        staff = request.env['cr.emp.staff'].search([('id', '=', staff_id)]).read(
            fields=['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'sex',
                    'birthday', 'photo_url'])
        total_scores = request.env['cr.emp.score'].search(
            [('staff_id', '=', int(staff_id)), ('year', '=', str(now.year))],
            order='month').read(fields=['total_score', 'level', 'month'])
        faults = request.env['cr.emp.score.item'].search(
            [('staff_id', '=', int(staff_id)), ('year', '=', str(now.year))], order='time').read(
            fields=['time', 'month', 'fault_type_id', 'fault_nature_type', 'fault_nature_id', 'survey', 'sub_score'])

        moneys = request.env['cr.emp.inspire'].search([('staff_id', '=', int(staff_id)), ('year', '=', str(now.year))],
                                                      order='month').read(
            fields=['year', 'month', 'sub_money', 'add_money', 'end_money'])
        for i in total_scores:
            i.update({'level': '优秀' if i['level'] == '0' else '合格' if i['level'] == '1' else '失信'})
        for i in faults:
            faults_nature_ids = request.env['cr.emp.fault.nature'].search([('id', 'in', i['fault_nature_id'])]).read()
            i.update({'fault_nature_id': [j['name'] for j in faults_nature_ids]})
            i.update({'fault_nature_type': '自我暴露' if i['fault_nature_type'] == 'self' else '他人指出' if i[
                                                                                                         'fault_nature_type'] == 'other' else '检查发现' if
            i['fault_nature_type'] == 'check' else '-'})
            i.update({'date': '%s-%s' % (i['time'].month, i['time'].day)})
            i.pop('time')
        result = {}
        # _logger.info('积分' + str(total_scores))
        # _logger.info('问题' + str(faults))
        # _logger.info('考核' + str(moneys))
        score_default = {
            "level": "-",
            "total_score": '-'
        }
        fault_default = {"date": "-",
                         "fault_nature_id": '-',
                         "fault_nature_type": "-",
                         "fault_type_id": '-',
                         "sub_score": '-',
                         "survey": '-'
                         }
        money_default = {"add_money": '-',
                         "end_money": '-',
                         "sub_money": '-',
                         }
        score, fault, money = {}, [], {}
        for index in range(1, 13):
            score.update(
                {'month%s' % str(index): i if i.get('month') == str(index) else score_default for i in total_scores})
            fault.append([i if i.get('month') == str(index) else fault_default for i in faults])
            money.update({'month%s' % str(index): i if i.get('month') == str(index) else money_default for i in moneys})
        result.update({'staff_info': staff[0], 'score': score, 'fault': fault, 'money': money})

        return get_error_message(result)


class CrEmpWarningController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'time', 'warning_detail_ids', 'id']

    @http.route('/emp/score/warning/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def warning_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            _logger.info(args)
            result = request.env['cr.emp.warning'].search(args=args, offset=limit['offset'],
                                                          limit=limit['limit'],
                                                          order=limit['sorted'])
            result = result.read()
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.warning'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                      order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.warning'].search_read(domain=[('id', 'in', ids)],
                                                                   fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')


class CrEmpWarningItemController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'warning_id', 'warning_card_id',
                'warning_staff_id',
                'id', 'time', 'warning_fault', 'measures']

    def get_update_fields(self):
        return ['staff_id', 'warning_card_id', 'time', 'warning_fault', 'measures', 'warning_staff_id']

    @http.route('/emp/score/warning_item/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def warning_item_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.warning.item'].search_read(domain=args, offset=limit['offset'],
                                                                    limit=limit['limit'],
                                                                    order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.warning.item'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                           order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.warning.item'].search_read(domain=[('id', 'in', ids)],
                                                                        fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/warning_item/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def warning_item_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        # # #_logger.info(args)
        result = request.env['cr.emp.warning.item'].create(args)
        if result:
            id = result[0].id
            fields = self.get_fields()
            result = request.env['cr.emp.warning.item'].search_read(domain=[('id', '=', id)],
                                                                    fields=fields)
            result = get_result(result, fields + ['id'])
            # # #_logger.info(result)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        else:
            return get_error_message(1)
        try:
            pass
        except:
            return get_error_message(1)

    @http.route('/emp/score/warning_item/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def warning_item_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {}
        args = add_to_args(args, fields, kwargs)
        result = request.env['cr.emp.warning.item'].search(args=[('id', '=', id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/warning_item/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def warning_item_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['cr.emp.warning.item'].search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)


class CrEmpTolerateController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):

        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id', 'fault_type_id', 'fault_nature_type',
                'fault_nature_id', 'time', 'id']

    @http.route('/emp/score/tolerate/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def tolerate_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.tolerate'].search_read(domain=args, offset=limit['offset'],
                                                                limit=limit['limit'],
                                                                order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.tolerate'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                       order=limit['sorted'], count=limit['count'])
        if result:
            ids = result.ids
            result = request.env['cr.emp.tolerate'].search_read(domain=[('id', 'in', ids)],
                                                                fields=fields)
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        else:
            return get_error_message('暂无数据')
        try:
            pass
        except:
            return get_error_message('暂无数据')


class CrEmpCorrectController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):

        return ['name', 'card_id', 'ws_id', 'team_id', 'post_id', 'staff_id',
                'handle_num', 'observe_time',
                'is_stop', 'time', 'id']

    @http.route('/emp/score/correct/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def correct_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            args = data2args(data, args, fields)
            result = request.env['cr.emp.correct'].search_read(domain=args, offset=limit['offset'],
                                                               limit=limit['limit'],
                                                               order=limit['sorted'])
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['cr.emp.correct'].search(args=args, offset=limit['offset'], limit=limit['limit'],
                                                      order=limit['sorted'], count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = request.env['cr.emp.correct'].search_read(domain=[('id', 'in', ids)],
                                                                   fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')


class CrEmpUserController(http.Controller):
    # if user must be authenticated use auth="user"

    def get_fields(self):
        return ['name', 'card_id', 'cr_emp_ws_id', 'cr_emp_type', 'id']

    def get_update_fields(self):
        return ['name', 'card_id', 'cr_emp_ws_id', 'cr_emp_type', 'id']

    @http.route('/emp/score/user/list', type='http', auth="user", csrf=False, method=["GET"],
                website=True, cors="*")
    def user_list(self, data=None):
        # # #_logger.info(data)
        data = json.loads(data)
        fields = self.get_fields()
        args = []
        limit = base_limit.copy()
        if data:
            limit = change_base_limit(limit, data)
            _logger.info(str(limit))
            args = data2args(data, args, fields)
            # #_logger.info(limit)
            # #_logger.info(args)
            result = request.env['res.users'].sudo().search(args=[('cr_emp_type', '!=', 'none')] + args,
                                                            offset=limit['offset'],
                                                            limit=limit['limit'],
                                                            order='create_date desc')
            result = result.read()
            result = get_result(result, fields + ['id'])
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)

        result = request.env['res.users'].sudo().search(args=[('cr_emp_type', '!=', 'none')] + args,
                                                        offset=limit['offset'], limit=limit['limit'],
                                                        order='create_date desc', count=limit['count'])
        try:
            if result:
                ids = result.ids
                result = result.read(fields=fields)
                result = get_result(result, fields + ['id'])
                return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
            else:
                return get_error_message('暂无数据')
        except:
            return get_error_message('暂无数据')

    @http.route('/emp/score/user/create', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def user_create(self, **kwargs):
        fields = self.get_update_fields()
        args = {'login': kwargs.get('card_id'), 'password': kwargs.get('password'),
                'card_id': kwargs.get('card_id'), 'cr_emp_type': kwargs.get('cr_emp_type')}
        cr_emp_ws_id = kwargs.get('cr_emp_ws_id')
        if cr_emp_ws_id:
            args.update({'cr_emp_ws_id': cr_emp_ws_id})
        partner_id = request.env['res.partner'].create({
            'name': kwargs.get('name')
        }).id
        args.update({'partner_id': partner_id})
        # # #_logger.info(args)
        result = request.env['res.users'].sudo().create(args)
        if result:
            id = result[0].id
            fields = self.get_fields()
            result = request.env['res.users'].sudo().search_read(domain=[('id', '=', id)],
                                                                 fields=fields)
            result = get_result(result, fields + ['id'])
            # # #_logger.info(result)
            return Response(json.dumps(result), content_type='application/json;charset=utf-8', status=200)
        else:
            _logger.info('失败1')
            return get_error_message(1)
        try:
            pass
        except:
            _logger.info('失败2')
            return get_error_message(1)

    @http.route('/emp/score/user/edit', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def user_edit(self, **kwargs):
        id = int(kwargs.get('id'))
        fields = self.get_update_fields()
        args = {'login': kwargs.get('card_id'), 'password': kwargs.get('password'),
                'card_id': kwargs.get('card_id'), 'cr_emp_type': kwargs.get('cr_emp_type')}
        cr_emp_ws_id = kwargs.get('cr_emp_ws_id')
        if cr_emp_ws_id:
            args.update({'cr_emp_ws_id': cr_emp_ws_id})
        result = request.env['res.users'].sudo().search(args=[('id', '=', id)])
        partner = request.env['res.partner'].sudo().search(args=[('id', '=', result.partner_id.id)])
        if not result:
            return get_error_message(0)
        try:
            result.write(args)
            partner.write({'name': kwargs.get('name')})
            return get_error_message(2)
        except:
            return get_error_message(3)

    @http.route('/emp/score/user/unlink', type='http', auth="user", csrf=False, method=["POST"],
                website=True, cors="*")
    def user_unlink(self, **kwargs):
        id = int(kwargs.get('id'))
        result = request.env['res.users'].sudo().search(args=[('id', '=', id)])
        if not result:
            return Response(json.dumps('未找到该数据'), content_type='application/json;charset=utf-8', status=200)
        try:
            result.unlink()
            if result:
                return Response(json.dumps('删除成功'), content_type='application/json;charset=utf-8', status=200)
        except:
            return Response(json.dumps('删除失败'), content_type='application/json;charset=utf-8', status=200)
